//
//  FLInterfaceDuoBao.m
//  Pods
//
//  Created by LinXiaoBin on 16/3/21.
//
//

#import "FLInterfaceForBusiness.h"
#import "FLInterfaceParam.h"
#import "BusinessInterfaceDefine.h"
#import "FLEncrypt.h"

#define ValueOrEmptyString(value) ((value)?(value):@"")

@interface FLInterfaceForBusiness()

@property (nonatomic, copy) NSString *action;
@property (nonatomic, copy) NSDictionary *params;

@end

@implementation FLInterfaceForBusiness

#pragma mark - ......::::::: Public :::::::......

- (void)requestAction:(NSString *)action
               params:(NSDictionary *)params
       httpSendMethod:(HttpSendMethod)httpSendMethod
{
    self.action = action;
    self.params = params;
    
    NSString *protocolVersion = kProtocolVersion1_0;
    if (httpSendMethod == HttpSendMethodGET) {
        NSDictionary *header = [self generateGETHeaderWithParams:self.params
                                                 protocolVersion:protocolVersion
                                                         signKey:kFLEmojiRequestSignKeyNOInternale];
        
        NSString* urlString = [NSString stringWithFormat:@"%@", kGetRequestBaseUrl];
        urlString = [self generateGETUrlWithBaseUrl:urlString params:self.params];
        urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        [self getURL:urlString header:header];
    } else if (httpSendMethod == HttpSendMethodPOST) {
        NSError *error = nil;
        NSData *orignData = [self requestBodyData:self.params error:&error];
        if (error) {
            [self failedRequest:error];
            return;
        }
        
        NSDictionary *header = [self generatePOSTHeaderWithBodyData:orignData protocolVersion:protocolVersion signKey:kFLEmojiRequestSignKeyNOInternale];
        NSString* url = [NSString stringWithFormat:@"%@", kPostRequestBaseUrl];
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [self postURL:url header:header dataBody:orignData];
    }
}


#pragma mark - ......::::::: Private :::::::......

- (NSData *)requestBodyData:(NSDictionary *)dict error:(NSError **)error
{
    if ([dict isKindOfClass:[NSDictionary class]]) {
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dict];
        NSMutableDictionary *copyParamsDict = [NSMutableDictionary dictionaryWithDictionary:params];
        [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if ([obj isKindOfClass:[NSData class]]) {
                if ([(NSData *)obj length] > kMaxUploadDataSzie) { //上传资源限制
                    *error = [self errorWithDomain:self.urlString code:FLInterfaceErrorCodeParamError message:@"上传资源不能超过3M"];
                    return;
                }
                
                //base64传输
                NSString *encodeString = [GTMBase64 stringByEncodingData:obj];
                [copyParamsDict setObject:encodeString forKey:key];
            }
        }];
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:copyParamsDict options:NSJSONWritingPrettyPrinted error:NULL];
        return data;
    }
    return nil;
}

/**
 *  生成POST方式发送请求的请求头信息
 *
 *  @param bodyData 发送内容
 *  @param version  Version
 *  @param signKey  signkey
 */
- (NSDictionary *)generatePOSTHeaderWithBodyData:(NSData *)bodyData protocolVersion:(NSString *)version signKey:(NSString*)signKey {
    
    NSString *sessionId = ValueOrEmptyString([self sessionID]);
    version = (version ? version : kProtocolVersion1_0);
    
    NSString* bodyString = nil;
    if (bodyData) {
        bodyString = [[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding];
    }
    bodyString = ValueOrEmptyString(bodyString);
    NSString *signString = [NSString stringWithFormat:@"%@%@%@%@%@",
                            sessionId, version, bodyString, signKey, nil];
    NSString *sign = [PHMD5String md5:signString];
    NSDictionary *dict = @{@"ProtocolVersion": version,
                           @"SessionId": sessionId,
                           @"Sign": sign};
    return dict;
}

/**
 *  生成GET方式发送请求的请求头信息
 *
 *  @param params 发送内容
 *  @param version  Version
 *  @param signKey  signkey
 */
- (NSDictionary *)generateGETHeaderWithParams:(NSDictionary *)params
                              protocolVersion:(NSString *)version
                                      signKey:(NSString*)signKey {
    
    NSString *sessionId = ValueOrEmptyString([self sessionID]);
    version = (version ? version : kProtocolVersion1_0);
    
    NSArray* sortedKeys = [[params allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString*  _Nonnull obj1, NSString*  _Nonnull obj2) {
         return [obj1 compare:obj2];
    }];
    
    NSMutableString* queryString = [NSMutableString new];
    for (NSString* key in sortedKeys) {
        id value = params[key];
        if ([value isKindOfClass:[NSString class]]) {
            [queryString appendString:value];
        }else if([value isKindOfClass:[NSNumber class]]){
            [queryString appendString:[value stringValue]];
        }
    }
    
    NSString *signString = [NSString stringWithFormat:@"%@%@%@%@%@",
                            sessionId, version, queryString, signKey, nil];
    
    NSString *sign = [PHMD5String md5:signString];
    
    NSDictionary *dict = @{@"ProtocolVersion": ValueOrEmpty(version),
                           @"SessionId": ValueOrEmpty(sessionId),
                           @"Sign": ValueOrEmpty(sign)};
    return dict;
}

/**
 *  生成GET方式请求的带有参数的URL
 *
 *  @param baseUrl 请求URL
 *  @param params  请求参数
 */
- (NSString*)generateGETUrlWithBaseUrl:(NSString*)baseUrl params:(NSDictionary*)params {
    if (baseUrl == nil || baseUrl.length == 0) {
        return nil;
    }
    NSMutableString* getUrl = [NSMutableString stringWithString:baseUrl];
    __block NSMutableArray* queryArr = [NSMutableArray array];
    [params enumerateKeysAndObjectsUsingBlock:^(NSString*  _Nonnull key, NSString*  _Nonnull obj, BOOL * _Nonnull stop) {
        [queryArr addObject:[NSString stringWithFormat:@"%@=%@", key, obj]];
    }];
    if (![[getUrl substringWithRange:NSMakeRange(getUrl.length-1, 1)] isEqualToString:@"?"]) {
        [getUrl appendString:@"?"];
    }
    [getUrl appendString:[queryArr componentsJoinedByString:@"&"]];
    return getUrl;
}

- (NSString *)sessionID
{
    NSString *result = nil;
    id<FLInterfaceBusinessParamDelegate> delegate = self.paramDelegate;
    if ([delegate respondsToSelector:@selector(pSessionID:)]) {
        result = [delegate pSessionID:self];
    }
    return result;
}

@end
